<template>
	<view class="JGoodsFilter" :class="customClass">
		<!-- 搜索栏 -->
		<view v-if="showSearch" class="search-bar">
			<view class="search-input">
				<input 
					v-model="searchKeyword" 
					:placeholder="searchPlaceholder"
					@input="onSearchInput"
					@confirm="onSearchConfirm"
					class="input"
				/>
				<view class="search-btn" @click="onSearchConfirm">
					<text class="search-icon">🔍</text>
				</view>
			</view>
		</view>
		
		<!-- 筛选条件栏 -->
		<view class="filter-bar" :style="filterBarStyle">
			<view 
				v-for="(item, index) in filterOptions" 
				:key="item.key || index"
				class="filter-item" 
				:class="{ 
					active: currentFilter === item.key,
					'has-arrow': item.hasArrow,
					'custom-item': item.custom
				}" 
				@click="handleFilterClick(item)"
			>
				<text>{{ item.label }}</text>
				<view v-if="item.hasArrow" class="arrow-container">
					<text class="arrow" :class="{ active: item.arrow === 'asc' }">▲</text>
					<text class="arrow" :class="{ active: item.arrow === 'desc' }">▼</text>
				</view>
				<view v-if="item.badge" class="filter-badge">{{ item.badge }}</view>
			</view>
		</view>
		
		<!-- 筛选弹窗 -->
		<view v-if="showFilterModal" class="filter-modal" @click="closeFilterModal">
			<view class="modal-content" @click.stop>
				<view class="modal-header">
					<text class="modal-title">{{ filterModalTitle }}</text>
					<text class="close-btn" @click="closeFilterModal">✕</text>
				</view>
				<view class="modal-body">
					<view v-for="(group, groupIndex) in filterGroups" :key="groupIndex" class="filter-group">
						<text class="group-title">{{ group.title }}</text>
						<view class="group-options">
							<view 
								v-for="(option, optionIndex) in group.options" 
								:key="optionIndex"
								class="option-item"
								:class="{ active: isOptionSelected(group.key, option.value) }"
								@click="toggleOption(group.key, option.value)"
							>
								<text>{{ option.label }}</text>
							</view>
						</view>
					</view>
				</view>
				<view class="modal-footer">
					<view class="reset-btn" @click="resetFilter">重置</view>
					<view class="confirm-btn" @click="confirmFilter">确定</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
export default {
	name: 'JGoodsFilter',
	props: {
		// 基础配置
		customClass: {
			type: String,
			default: ''
		},
		theme: {
			type: String,
			default: 'default', // default, primary, success, warning, danger
			validator: value => ['default', 'primary', 'success', 'warning', 'danger'].includes(value)
		},
		
		// 搜索配置
		showSearch: {
			type: Boolean,
			default: false
		},
		searchPlaceholder: {
			type: String,
			default: '请输入搜索关键词'
		},
		searchDebounce: {
			type: Number,
			default: 300
		},
		
		// 筛选选项配置
		filterOptions: {
			type: Array,
			default: () => [
				{ key: 'comprehensive', label: '综合', hasArrow: false },
				{ key: 'sales', label: '销量', hasArrow: true, arrow: 'desc' },
				{ key: 'price', label: '价格', hasArrow: true, arrow: 'asc' },
				{ key: 'filter', label: '筛选', hasArrow: false, custom: true }
			]
		},
		
		// 筛选弹窗配置
		filterGroups: {
			type: Array,
			default: () => [
				{
					key: 'category',
					title: '分类',
					options: [
						{ label: '全部', value: 'all' },
						{ label: '爆品', value: 'hot' },
						{ label: '新品', value: 'new' }
					]
				},
				{
					key: 'priceRange',
					title: '价格区间',
					options: [
						{ label: '不限', value: 'all' },
						{ label: '0-50元', value: '0-50' },
						{ label: '50-100元', value: '50-100' },
						{ label: '100元以上', value: '100+' }
					]
				}
			]
		},
		filterModalTitle: {
			type: String,
			default: '筛选条件'
		},
		
		// 样式配置
		filterBarStyle: {
			type: Object,
			default: () => ({})
		},
		
		// 数据源
		goodsList: {
			type: Array,
			default: () => []
		},
		
		// 初始值
		initialFilter: {
			type: String,
			default: 'comprehensive'
		},
		initialSearchKeyword: {
			type: String,
			default: ''
		}
	},
	data() {
		return {
			searchKeyword: this.initialSearchKeyword,
			currentFilter: this.initialFilter,
			showFilterModal: false,
			selectedOptions: {},
			searchTimer: null
		};
	},
	computed: {
		themeClass() {
			return `theme-${this.theme}`;
		},
		filteredGoods() {
			let result = [...this.goodsList];

			// 搜索筛选
			if (this.searchKeyword) {
				result = result.filter((item) => {
					const searchFields = ['name', 'title', 'description'];
					return searchFields.some(field => 
						item[field] && item[field].toLowerCase().includes(this.searchKeyword.toLowerCase())
					);
				});
			}

			// 排序
			this.applySorting(result);

			// 筛选条件
			this.applyFilters(result);

			return result;
		}
	},
	watch: {
		searchKeyword(newVal) {
			this.$emit('search-change', newVal);
		},
		currentFilter(newVal) {
			this.$emit('filter-change', newVal);
		},
		selectedOptions: {
			handler(newVal) {
				this.$emit('options-change', newVal);
			},
			deep: true
		}
	},
	methods: {
		// 搜索相关
		onSearchInput(e) {
			this.searchKeyword = e.detail.value;
			this.debounceSearch();
		},
		onSearchConfirm() {
			this.$emit('search', this.searchKeyword);
		},
		debounceSearch() {
			clearTimeout(this.searchTimer);
			this.searchTimer = setTimeout(() => {
				this.$emit('search', this.searchKeyword);
			}, this.searchDebounce);
		},
		
		// 筛选相关
		handleFilterClick(item) {
			if (item.custom) {
				this.toggleFilterModal();
				return;
			}
			
			if (item.hasArrow) {
				this.toggleArrow(item);
			} else {
				this.setCurrentFilter(item.key);
			}
		},
		setCurrentFilter(key) {
			this.currentFilter = key;
			this.$emit('filter-change', key);
		},
		toggleArrow(item) {
			const newArrow = item.arrow === 'asc' ? 'desc' : 'asc';
			item.arrow = newArrow;
			this.setCurrentFilter(item.key);
			this.$emit('sort-change', { key: item.key, order: newArrow });
		},
		
		// 筛选弹窗相关
		toggleFilterModal() {
			this.showFilterModal = !this.showFilterModal;
		},
		closeFilterModal() {
			this.showFilterModal = false;
		},
		isOptionSelected(groupKey, optionValue) {
			return this.selectedOptions[groupKey] && this.selectedOptions[groupKey].includes(optionValue);
		},
		toggleOption(groupKey, optionValue) {
			if (!this.selectedOptions[groupKey]) {
				this.$set(this.selectedOptions, groupKey, []);
			}
			
			const index = this.selectedOptions[groupKey].indexOf(optionValue);
			if (index > -1) {
				this.selectedOptions[groupKey].splice(index, 1);
			} else {
				this.selectedOptions[groupKey].push(optionValue);
			}
		},
		resetFilter() {
			this.selectedOptions = {};
			this.$emit('filter-reset');
		},
		confirmFilter() {
			this.closeFilterModal();
			this.$emit('filter-confirm', this.selectedOptions);
		},
		
		// 数据处理
		applySorting(result) {
			const currentFilterItem = this.filterOptions.find(item => item.key === this.currentFilter);
			if (!currentFilterItem || !currentFilterItem.hasArrow) return;
			
			const order = currentFilterItem.arrow;
			const key = currentFilterItem.key;
			
			switch (key) {
				case 'sales':
					result.sort((a, b) => order === 'asc' ? a.sales - b.sales : b.sales - a.sales);
					break;
				case 'price':
					result.sort((a, b) => order === 'asc' ? a.price - b.price : b.price - a.price);
					break;
				case 'time':
					result.sort((a, b) => order === 'asc' ? new Date(a.time) - new Date(b.time) : new Date(b.time) - new Date(a.time));
					break;
			}
		},
		applyFilters(result) {
			Object.keys(this.selectedOptions).forEach(groupKey => {
				const selectedValues = this.selectedOptions[groupKey];
				if (selectedValues.length === 0) return;
				
				result = result.filter(item => {
					// 这里可以根据具体的筛选逻辑来处理
					// 例如根据分类、价格区间等
					return this.matchFilterCondition(item, groupKey, selectedValues);
				});
			});
		},
		matchFilterCondition(item, groupKey, selectedValues) {
			// 这里实现具体的筛选逻辑
			// 可以根据实际需求来扩展
			switch (groupKey) {
				case 'category':
					return selectedValues.includes('all') || selectedValues.includes(item.category);
				case 'priceRange':
					return selectedValues.includes('all') || this.isInPriceRange(item.price, selectedValues);
				default:
					return true;
			}
		},
		isInPriceRange(price, ranges) {
			return ranges.some(range => {
				switch (range) {
					case '0-50':
						return price >= 0 && price <= 50;
					case '50-100':
						return price > 50 && price <= 100;
					case '100+':
						return price > 100;
					default:
						return true;
				}
			});
		},
		
		// 公共方法
		getCurrentFilter() {
			return this.currentFilter;
		},
		getSelectedOptions() {
			return this.selectedOptions;
		},
		setFilterOptions(options) {
			this.filterOptions = options;
		},
		resetAll() {
			this.searchKeyword = '';
			this.currentFilter = this.initialFilter;
			this.selectedOptions = {};
			this.$emit('reset');
		}
	}
};
</script>

<style lang="less" scoped>
.JGoodsFilter {
	background-color: #f5f5f5;
	
	// 搜索栏
	.search-bar {
		background: #fff;
		padding: 20rpx;
		border-bottom: 1rpx solid #eee;
		
		.search-input {
			display: flex;
			align-items: center;
			background: #f5f5f5;
			border-radius: 25rpx;
			padding: 0 20rpx;
			height: 70rpx;
			
			.input {
				flex: 1;
				font-size: 28rpx;
				color: #333;
				background: transparent;
				border: none;
				outline: none;
			}
			
			.search-btn {
				width: 50rpx;
				height: 50rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				
				.search-icon {
					font-size: 32rpx;
					color: #666;
				}
			}
		}
	}
	
	// 筛选条件栏
	.filter-bar {
		display: flex;
		background: #fff;
		border-bottom: 1rpx solid #eee;
		
		.filter-item {
			flex: 1;
			text-align: center;
			padding: 20rpx 0;
			font-size: 26rpx;
			color: #666;
			line-height: 1;
			position: relative;
			display: flex;
			align-items: center;
			justify-content: center;
			transition: all 0.3s ease;
			
			&.active {
				color: #246ef9;
				font-weight: 600;
			}
			
			&.has-arrow {
				.arrow-container {
					display: flex;
					flex-direction: column;
					margin-left: 8rpx;
					
					.arrow {
						font-size: 16rpx;
						line-height: 1;
						color: #ccc;
						transition: color 0.3s ease;
						
						&.active {
							color: #246ef9;
						}
					}
				}
			}
			
			&.custom-item {
				background: #f8f9fa;
				margin: 10rpx;
				border-radius: 20rpx;
				flex: none;
				padding: 10rpx 20rpx;
				min-width: 120rpx;
				
				&.active {
					background: #246ef9;
					color: #fff;
				}
			}
			
			.filter-badge {
				position: absolute;
				top: 5rpx;
				right: 5rpx;
				background: #ff4d4f;
				color: #fff;
				font-size: 18rpx;
				padding: 2rpx 6rpx;
				border-radius: 10rpx;
				min-width: 20rpx;
				text-align: center;
				line-height: 1;
			}
		}
	}
	
	// 筛选弹窗
	.filter-modal {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background: rgba(0, 0, 0, 0.5);
		z-index: 1000;
		display: flex;
		align-items: flex-end;
		
		.modal-content {
			background: #fff;
			width: 100%;
			max-height: 80vh;
			border-radius: 20rpx 20rpx 0 0;
			overflow: hidden;
			
			.modal-header {
				display: flex;
				align-items: center;
				justify-content: space-between;
				padding: 30rpx 40rpx;
				border-bottom: 1rpx solid #eee;
				
				.modal-title {
					font-size: 32rpx;
					font-weight: 600;
					color: #333;
				}
				
				.close-btn {
					font-size: 40rpx;
					color: #999;
					width: 60rpx;
					height: 60rpx;
					display: flex;
					align-items: center;
					justify-content: center;
				}
			}
			
			.modal-body {
				padding: 30rpx 40rpx;
				max-height: 60vh;
				overflow-y: auto;
				
				.filter-group {
					margin-bottom: 40rpx;
					
					.group-title {
						font-size: 28rpx;
						font-weight: 600;
						color: #333;
						margin-bottom: 20rpx;
						display: block;
					}
					
					.group-options {
						display: flex;
						flex-wrap: wrap;
						gap: 20rpx;
						
						.option-item {
							padding: 15rpx 30rpx;
							background: #f5f5f5;
							border-radius: 25rpx;
							font-size: 26rpx;
							color: #666;
							transition: all 0.3s ease;
							
							&.active {
								background: #246ef9;
								color: #fff;
							}
						}
					}
				}
			}
			
			.modal-footer {
				display: flex;
				padding: 30rpx 40rpx;
				border-top: 1rpx solid #eee;
				gap: 20rpx;
				
				.reset-btn, .confirm-btn {
					flex: 1;
					height: 80rpx;
					display: flex;
					align-items: center;
					justify-content: center;
					border-radius: 40rpx;
					font-size: 28rpx;
					font-weight: 600;
					transition: all 0.3s ease;
				}
				
				.reset-btn {
					background: #f5f5f5;
					color: #666;
					
					&:active {
						background: #e0e0e0;
					}
				}
				
				.confirm-btn {
					background: #246ef9;
					color: #fff;
					
					&:active {
						background: #1e5bb8;
					}
				}
			}
		}
	}
	
	// 主题样式
	&.theme-primary {
		.filter-item.active {
			color: #246ef9;
		}
		.arrow.active {
			color: #246ef9;
		}
		.custom-item.active {
			background: #246ef9;
		}
		.confirm-btn {
			background: #246ef9;
		}
	}
	
	&.theme-success {
		.filter-item.active {
			color: #52c41a;
		}
		.arrow.active {
			color: #52c41a;
		}
		.custom-item.active {
			background: #52c41a;
		}
		.confirm-btn {
			background: #52c41a;
		}
	}
	
	&.theme-warning {
		.filter-item.active {
			color: #faad14;
		}
		.arrow.active {
			color: #faad14;
		}
		.custom-item.active {
			background: #faad14;
		}
		.confirm-btn {
			background: #faad14;
		}
	}
	
	&.theme-danger {
		.filter-item.active {
			color: #ff4d4f;
		}
		.arrow.active {
			color: #ff4d4f;
		}
		.custom-item.active {
			background: #ff4d4f;
		}
		.confirm-btn {
			background: #ff4d4f;
		}
	}
}
</style>
